import { Component, DefineComponent, defineComponent, EmitsOptions, SetupContext, watchEffect } from 'vue';

/**
 * 生成组件
 *
 * @author chitanda
 * @date 2021-05-18 11:05:46
 * @export
 * @param {*} ComponentClass 组件类
 * @param {*} [props] 传入的输入参数
 * @return {*}
 */
export function GenerateComponent(
  ComponentClass: any,
  props?: any,
  components?: Record<string, Component>,
): DefineComponent<any> {
  return defineComponent({
    name: ComponentClass.name,
    props,
    components,
    setup(props: any, ctx: SetupContext<EmitsOptions>) {
      const c = new ComponentClass(props, ctx);
      c.setup();
      return { c };
    },
    beforeMount() {
      this.c.forceUpdate = () => {
        this.$forceUpdate();
      };
      this.c.$tl = (key: string, value: string) => {
        if (this.$tl) {
          return this.$tl(key, value);
        } else {
          return value;
        }
      };
      watchEffect(() => {
        this.c.watchEffect();
      });
      this.c.init();
    },
    unmounted() {
      this.c.unmounted();
    },
    render() {
      return this.c.render();
    },
  });
}
